package com.powernode.conifg;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.constant.ResourceConstant;
import com.powernode.filter.TokenTranslateFilter;
import com.powernode.model.Result;
import com.powernode.utils.MyAllowPathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;
import java.io.PrintWriter;

/**
 * @Author LF
 * projectName:today-shop
 * description:
 * time:2022-09-18 15:57
 */
@Configuration
public class ResouceConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private TokenTranslateFilter tokenTranslateFilter;

    /**
     * 这个是资源服务器的配置
     * 处理token解析 以及接口放行 等配置
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        // 在认证之前 我们自己做解析  相当于跳过认证
        http.addFilterBefore(tokenTranslateFilter, UsernamePasswordAuthenticationFilter.class);
        // 如果token没带 并且security也没有放行 就要走我们这里
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
        // 配置业务上放行的接口
        http.authorizeRequests()
                .antMatchers(MyAllowPathUtil.securityAllowPaths())
                .permitAll();
        // 其他所有的接口都必须认证后才可以访问
        http.authorizeRequests()
                .anyRequest()
                .authenticated();
    }

    @Bean
    public AccessDeniedHandler accessDeniedHandler() {
        return (request, response, accessDeniedException) -> {
            response.setCharacterEncoding("UTF-8");
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            Result<Object> result = Result.fail(HttpStatus.UNAUTHORIZED.value(), "访问被拒绝");
            ObjectMapper objectMapper = new ObjectMapper();
            String s = objectMapper.writeValueAsString(result);
            PrintWriter writer = response.getWriter();
            writer.write(s);
            writer.flush();
            writer.close();
        };
    }
}
